<template>
  <div class="as-dropdown"
       :class="[size?'as-dropdown--'+size:'','as-dropdown--'+placement]"
       ref="asDropdown"
       @mouseleave="leaveDropdown"
       @mouseenter="enterDropdown">
    <div @click="trigglerDropdown">
      <slot></slot>
    </div>
    <transition name="as-room-to-top">
      <div v-show="hoverDropdown && !close">
        <slot name="dropdown"></slot>
      </div>
    </transition>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: "AsDropdown",
  componentName: "AsDropdown",
  props: {
    size: String,
    triggler: String,
    placement: { type: String, default: "bottom" }
  },
  data() {
    return {
      hoverDropdown: false,
      timeout: null,
      close: false
    };
  },
  watch: {
    hoverDropdown(newVal) {
      this.$emit("change-visible", newVal);
    }
  },
  mounted() {
    window.addEventListener("click", this.blurInput);
    this.$on("handCommand", val => {
      this.$emit("command", val);
      this.close = true;
      this.hoverDropdown = false;

      setTimeout(() => {
        this.close = false;
      }, 800);
    });
  },
  destroyed() {
    window.removeEventListener("click", this.blurInput);
  },
  methods: {
    blurInput(e) {
      let contain = this.$refs.asDropdown.contains(e.target);

      if (!contain) {
        this.hoverDropdown = false;
      }
    },
    trigglerDropdown() {
      if (this.triggler === "click") {
        clearTimeout(this.timeout);
        this.hoverDropdown = !this.hoverDropdown;
      }
    },
    enterDropdown() {
      clearTimeout(this.timeout);
      if (this.triggler !== "click") {
        this.hoverDropdown = true;
      }
    },
    leaveDropdown() {
      if (this.triggler !== "click") {
        this.timeout = setTimeout(() => {
          this.hoverDropdown = false;
        }, 800);
      }
    }
  }
};
</script>
